# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
from cmsdj.categories.models import Category
from django.contrib.comments.moderation import CommentModerator, moderator
from django.utils.http import urlquote
from django.template.defaultfilters import slugify
from django.contrib.sitemaps import ping_google
from cmsdj.util.keywords import get_keywords

class UserContent(User):
    class Meta:
        proxy = True

class Content (models.Model):
    #@todo: meter en configuración el tamaño de la descripción breve de una categoría, de momento lo dejo aquí
    LEN_MAX_SHORT_DESC = 512
    
    title = models.CharField ( max_length = 255 )
    description = models.TextField ( blank=True )
    created = models.DateTimeField (auto_now_add = True)
    modified = models.DateTimeField (auto_now = True)
    parent = models.ForeignKey ('Content', default = None, blank = True, null = True)
    user = models.ForeignKey ('UserContent', related_name = 'creador')
    categories = models.ManyToManyField(Category)
    slug = models.SlugField ( unique=True, null=False, blank=True)
    published = models.BooleanField ( null = False , blank = False, default = True)

    def __unicode__ (self):
        if (self.published):
            return u'' + self.title
        else:
            return u'' + self.title + ' (no pub)'
    
    def __get_short_description__ (self):
        return unicode(self.description)[0 : self.LEN_MAX_SHORT_DESC]
    
    def title4url(self):
        return urlquote(self.title)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Content, self).save(*args, **kwargs)
        try:
            ping_google()
        except Exception:
            pass
        
    def get_childs(self):
        return Content.objects.all().filter(parent=self).filter(published=True)

    def is_root (self):
        return self.parent == None
    
    def get_absolute_url (self):
        return '/content/' + str(self.slug)
    
    def get_keywords(self):
        return get_keywords(self.description + self.title)
    
    @staticmethod
    def get_roots():
        return Content.objects.filter( parent__isnull=True )
    
    @staticmethod
    def get_by_category(category):
        contents = []
        for content in Content.objects.filter(published=True).all():
            for category_aux in content.categories.values():
                try:
                    add_content = category_aux['name'] == category.name
                except UnicodeEncodeError:
                    add_content = category_aux['name'].encode('utf16') == category.name.encode('utf16')
                if ( add_content ):
                    contents.append(content)
                    continue
        return contents
    
    def get_url(self):
        return "/content/" + str(self.id)
    
    def get_parent (self):
        if (self.parent != None and self.parent.published == True ):
            return self.parent
        else:
            return None
        
    
    @staticmethod
    def get_by_date_modified():
        return Content.objects.filter(published=True).order_by('-modified')
        
    @staticmethod
    def get_by_date_created():
        return Content.objects.filter(published=True).order_by('-created')

    short_description = property ("__get_short_description__", "Return a brief description")
    
class ContentModerator(CommentModerator):
    email_notification = True
    auto_close_field   = 'created'
    # Close the comments after 7 days.
    #close_after        = 7

moderator.register(Content, ContentModerator)
